﻿// -----------------------------------------------------------------------
// <copyright file="Context.cs" company="AGR">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace AGR.Data.Repository
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using AGR.Data.Context;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public sealed class ContextHelper
    {
        private static ContextHelper _instance;
        private static object _lockThis = new object();

        private static AGRContext _context;

        private ContextHelper()
        {
            _context = new AGRContext();
        }

        public static ContextHelper GetInstance()
        {
            lock (_lockThis)
            {
                if (_instance == null)
                {
                    _instance = new ContextHelper();
                }
            }

            return _instance;
        }

        internal AGRContext GetContext()
        {
            return _context;
        }

        public void StartChanges()
        {
            this.EndChanges();

            if (_context == null)
                _context = new AGRContext();

            _disposed = false;
        }

        private void EndChanges()
        {
            if (_context != null)
                _context.Dispose();

            _context = null;
        }

        public void SubmitChanges()
        {
            _context.SubmitChanges();
        }

        #region Dispose

        private bool _disposed = false;

        private void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    if (_context != null)
                        _context.Dispose();
                }
            }
            _disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
